package com.lam.common.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.lam.common.base.domain.Result;
import com.lam.common.components.file.FileDownloadUtil;
import com.lam.common.components.file.model.FileBusiTypeEnum;
import com.lam.common.components.file.model.FileDownloadInfo;
import com.lam.common.components.file.service.AttachFileService;
import com.lam.common.exception.BusinessException;
import com.lam.common.utils.ServletUtils;
import com.lam.common.utils.StringUtils;
import com.lam.common.utils.UriSchemeUtil;
import com.lam.common.utils.file.FileUploadUtil;
import com.lam.common.validate.ValidateUtil;
import com.lam.framework.operLog.annotation.Log;
import com.lam.framework.operLog.enums.BusinessType;
import com.lam.framework.operLog.enums.LogSave;

/**
 * 通用请求处理
 * 
 * @author lam
 */
@Log(title = "公共请求")
@RestController
@RequestMapping("/${adminPath}/common")
public class CommonController {
	
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private AttachFileService attachFileService;
	
	@Log(businessType = BusinessType.DOWNLOAD, oper = "下载文件")
	@GetMapping("/file")
	public void fileDownload(@RequestParam("s")String sign, @RequestParam("t")int type) {
		
		try {
			ServletUtils.outWriteFile(getDownloadInfo(type, sign).getPath(), MediaType.TEXT_HTML_VALUE);
		} catch (Exception e) {
			FileDownloadUtil.writeFail(ServletUtils.getResponse(), e, sign);
		}
	}
	
	@Log(businessType = BusinessType.DOWNLOAD, oper = "下载图片", logSave = LogSave.NO)
	@GetMapping("/img")
	public void img(@RequestParam("s")String sign, @RequestParam("t")int type) {
		
		ServletUtils.outWriteFile(getDownloadInfo(type, sign).getPath(), MediaType.IMAGE_JPEG_VALUE);
	}
	
	@Log(businessType = BusinessType.DOWNLOAD, oper = "下载图片数据", logSave = LogSave.NO)
	@GetMapping("/imgData")
	public Result imgBase64(@RequestParam("s")String sign, @RequestParam("t")int type) {
		
		return Result.ok(UriSchemeUtil.encode(getDownloadInfo(type, sign).getPath()));
	}
	
	private FileDownloadInfo getDownloadInfo(int type, String sign) {
		
		FileBusiTypeEnum fileType = FileBusiTypeEnum.valueFrom(type);
		ValidateUtil.validRequired(fileType, "无效的参数t！");
		ValidateUtil.validRequired(sign, "无效的参数s！");
		
		FileDownloadInfo filDownloadInfo = FileDownloadUtil.getDownloadInfo(fileType, sign);
		if(filDownloadInfo == null || StringUtils.isBlank(filDownloadInfo.getPath())) {
			logger.error("根据sign未找到文件记录，sign:{}", sign);
			throw new BusinessException("不存在的文件！");
		}
		return filDownloadInfo;
	}

	@Log(businessType = BusinessType.UPLOAD, oper = "附件上传")
	@PostMapping("/upload")
	public Result uploadElementFile(MultipartFile file, String busiModule){
		if(file.isEmpty()){
            return Result.ok();
        }
		String fileName = attachFileService.uploadFile(file, busiModule);
		
        return Result.ok().data(fileName);
	}
	
	@Log(businessType = BusinessType.UPLOAD, oper = "符文布编辑器文件上传")
	@PostMapping("/upload/tinymceEditor")
	public Result uploadTinymceEditorImages(MultipartFile file, String busiModule){
		
		String fileName =  attachFileService.uploadFile(file, busiModule);
        return Result.ok().data(FileUploadUtil.getResourceUrl() + fileName);
	}
	
//	@Log(businessType = BusinessType.DOWNLOAD, oper = "下载文件数据", logSave = LogSave.NO)
//	@GetMapping("/file/resource/**}")
//	public Result getFileResource(MultipartFile file, String busiModule){
//		
//		String fileName =  attachFileService.uploadFile(file, busiModule);
//        return Result.ok(FileUploadUtil.getResourceUrl() + fileName);
//	}
	
//	/**
//	 * 通用上传请求
//	 */
//	@Log(businessType = BusinessType.UPLOAD, oper = "上传文件")
//	@PostMapping("/upload")
//	public Result uploadFile(MultipartFile[] files) {
//		
//		// 上传文件路径
//		String dirPath = AppBaseConfig.me().getLocalAttachment().getAttachmentDir();
//		// 上传并返回新文件名称
//		List<String> fileList = ServletUtils.uploadStreamToFile(dirPath, files);
//		List<FileDownloadInfo> downloadList = new ArrayList<>();
//		for (String file : fileList) {
//			downloadList.add(FileDownloadUtil.createDownloadInfo(FileBusiTypeEnum.UPLOAD_TMP, file));
//		}
//		return Result.ok(downloadList);
//	}

}
